<?php

namespace App\Listeners\Kms;

use App\Events\Kms\DailyTaskCreateEvent;
use App\Models\Kms\Task\DailyTaskLogsModel;
use App\Models\Kms\Task\TaskNodesModel;
use App\Models\Kms\Task\TaskTemplateModel;
use App\Models\Kms\Task\TaskTemplateNodesModel;
use App\Models\Kms\Task\TaskTemplateNodesProcessorModel;
use App\Models\Kms\User\KmsUser;
use App\Service\Kms\Task\Common\BaseTask;
use App\Service\Kms\Task\Common\TaskService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;

class DailyTaskCreateListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param DailyTaskCreateEvent $event
     * @return void
     * @throws \Exception
     */
    public function handle(DailyTaskCreateEvent $event)
    {
        $dailyTaskLogsCollection = DailyTaskLogsModel::query()
                                                     ->where("uniqueSign", $event->uniqueSign)
                                                     ->get();

        // todo 获取所有审批人创建人信息
        $userIds = [];
        $dailyTaskLogsCollection->each(function (DailyTaskLogsModel $dailyTaskLogsModel) use (&$userIds) {
            $userIds = array_merge(
                $userIds,
                jsonToArr($dailyTaskLogsModel->approveUserIds, []),
                [$dailyTaskLogsModel->createdByUid, $dailyTaskLogsModel->handlerUserId]
            );
        });
        $userGroup = KmsUser::query()->whereIn("rmsUserId", array_unique($userIds))->get();

        // todo 创建任务
        $dailyTaskLogsCollection->each(function (DailyTaskLogsModel $dailyTaskLogsModel) use ($userGroup) {
            BaseTask::getTaskInstance($dailyTaskLogsModel->templateType)
                    ->handleTaskCreateEvent($dailyTaskLogsModel, $userGroup);
        });
    }

}
